package com.synjones.handsetS8L;

import android.app.Activity;
import android.content.Context;
import android.os.Build;
import android.os.Handler;

import com.synjones.cominterface.DataTransChannel;
import com.synjones.cominterface.ReaderInterface;
import com.synjones.idcard.IDcardReader;
import com.synjones.multireaderlib.CmdResponse;
import com.synjones.multireaderlib.MultiReader;

import java.io.File;

import android_serialport_api.SerialPort;


public class BIInterface implements ReaderInterface{
    DataTransChannel dataTransChannel;
    SerialPort serialPort;
    Activity activity;
    boolean isOpen=false;
    String path="S8EL1手持机";
    String samvID;
    final int DEF_BAUDRATE=115200;
    Context context;
    public BIInterface(){
        dataTransChannel=new DataTransChannel();
    }
    @Override
    public void setActivityAndHandler(Activity act, Handler mHandler) {
        this.activity=act;
    }

    @Override
    public void setContext(Context context) {
        this.context=context;
    }

    @Override
    public void release() {
        close();
        PowerUtil.power("0");
        serialPort=null;
    }

    @Override
    public boolean open() {
        if(isOpen()) {
            close();
            MyUtils.sleep(500);
        }
        //S8PowerControl.getInstance().setIDReaderPowerOn();
        int BaudrateArray[]={115200,57600,38400,19200,9600};
        for(int i=0;i<BaudrateArray.length;i++){
            isOpen=tryOpen(BaudrateArray[i]);
            if(isOpen){
                if(BaudrateArray[i]!=DEF_BAUDRATE)
                    isOpen=resetSerial();
                break;
            }
            close();
            MyUtils.sleep(500);
        }

        if(isOpen){
            getReader().setMaxRFByte(80);
        }

        return isOpen;
    }


    private IDcardReader getReader(){
        MultiReader multiReader=MultiReader.getReader();
        multiReader.setDataTransInterface(dataTransChannel);
        return new IDcardReader(multiReader);
    }

    private boolean resetSerial(){
        CmdResponse response=getReader().setBaudrate(DEF_BAUDRATE);
        if(response==null || !response.SwIs9000())
            return false;
        close();
        return tryOpen(DEF_BAUDRATE);
        //iDcardReader.setMaxRFByte(80);
    }


    private boolean tryOpen(int baudrate){
        PowerUtil.power("1");
        MyUtils.sleep(500);//使模块上电完成
        /* Open the serial port */
        try {
            String path="/dev/ttyS2" ;
            String dev=new Build().DEVICE;
            if (context!=null && "S80".equals(dev)){
                path="/dev/ttyS3";
            }
            serialPort = new SerialPort(new File(path), baudrate, 0);
            dataTransChannel.setInOutStream(serialPort.getInputStream(),serialPort.getOutputStream());
            dataTransChannel.open();
            long t=System.currentTimeMillis();
            while(System.currentTimeMillis()-t<3000){
                if(canReadSamv())
                    break;
                MyUtils.sleep(100);
            }

            //isOpen=true;
            return samvID!=null&&!samvID.isEmpty();
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }

    }

    public boolean canReadSamv(){
        samvID=getReader().getSamvIDStr();
        return !samvID.isEmpty();
    }

    @Override
    public void close() {
       if(serialPort!=null) {
           try {
               serialPort.close();
           }catch (Exception e){}
       }
        serialPort=null;
        isOpen = false;
        if(dataTransChannel!=null){
            try{
                dataTransChannel.close();
            }catch (Exception e){}
        }
        //S8PowerControl.getInstance().setIDReaderPowerOff();
        PowerUtil.power("0");
    }

    @Override
    public boolean isOpen() {
        return isOpen;
    }

    @Override
    public DataTransChannel getDataTransChannel() {
        return dataTransChannel;
    }

    @Override
    public String getDevName() {
        return path;
    }

    @Override
    public String getSamvID() {
        return samvID;
    }
}
